/**
 * Three.js 完整开发教程
 * 实现完整的Three.js开发流程和最佳实践
 */

// 导入 Three.js 模块
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.155.0/build/three.module.js';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/loaders/GLTFLoader.js';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/postprocessing/UnrealBloomPass.js';
import { FilmPass } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/postprocessing/FilmPass.js';
import { ShaderPass } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/postprocessing/ShaderPass.js';
import { CopyShader } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/shaders/CopyShader.js';

class ThreeJSApp {
    constructor() {
        // 基础组件
        this.canvas = null;
        this.renderer = null;
        this.scene = null;
        this.camera = null;
        this.controls = null;
        
        // 光源
        this.ambientLight = null;
        this.directionalLight = null;
        this.pointLights = [];
        
        // 交互
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();
        this.selectedObject = null;
        
        // 动画
        this.clock = new THREE.Clock();
        this.mixers = [];
        this.animatedObjects = [];
        
        // 后处理
        this.composer = null;
        this.renderPass = null;
        this.bloomPass = null;
        this.filmPass = null;
        
        // 场景管理
        this.currentScene = 'basic';
        this.sceneObjects = new Map();
        
        // 性能监控
        this.frameCount = 0;
        this.lastTime = performance.now();
        this.fps = 0;
        
        // 设置
        this.settings = {
            enableShadows: true,
            enablePostProcessing: false,
            wireframeMode: false,
            ambientIntensity: 0.4,
            directionalIntensity: 1.0
        };
        
        this.init();
    }
    
    /**
     * 1. 基础骨架搭建
     */
    init() {
        this.setupRenderer();
        this.setupScene();
        this.setupCamera();
        this.setupLights();
        this.setupControls();
        this.setupPostProcessing();
        this.setupEventListeners();
        this.createBasicScene();
        this.animate();
        
        // 隐藏加载界面
        setTimeout(() => {
            document.getElementById('loading').classList.add('hidden');
        }, 1000);
    }
    
    setupRenderer() {
        this.canvas = document.getElementById('webgl-canvas');
        
        this.renderer = new THREE.WebGLRenderer({
            canvas: this.canvas,
            antialias: true,
            alpha: true,
            powerPreference: 'high-performance'
        });
        
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        this.renderer.setClearColor(0x1a1a2e, 1);
        
        // 启用阴影
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        
        // 色调映射
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.0;
        
        // 物理正确的光照
        this.renderer.physicallyCorrectLights = true;
    }
    
    setupScene() {
        this.scene = new THREE.Scene();
        
        // 添加雾效
        this.scene.fog = new THREE.Fog(0x1a1a2e, 10, 100);
        
        // 设置环境贴图
        this.loadEnvironmentMap();
    }
    
    setupCamera() {
        this.camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth / window.innerHeight,
            0.1,
            1000
        );
        
        this.camera.position.set(5, 5, 5);
        this.camera.lookAt(0, 0, 0);
    }
    
    setupLights() {
        // 环境光
        this.ambientLight = new THREE.AmbientLight(0x404040, this.settings.ambientIntensity);
        this.scene.add(this.ambientLight);
        
        // 方向光（主光源）
        this.directionalLight = new THREE.DirectionalLight(0xffffff, this.settings.directionalIntensity);
        this.directionalLight.position.set(10, 10, 5);
        this.directionalLight.castShadow = true;
        
        // 优化阴影参数
        this.directionalLight.shadow.mapSize.width = 2048;
        this.directionalLight.shadow.mapSize.height = 2048;
        this.directionalLight.shadow.camera.near = 0.5;
        this.directionalLight.shadow.camera.far = 50;
        this.directionalLight.shadow.camera.left = -10;
        this.directionalLight.shadow.camera.right = 10;
        this.directionalLight.shadow.camera.top = 10;
        this.directionalLight.shadow.camera.bottom = -10;
        this.directionalLight.shadow.bias = -0.0001;
        
        this.scene.add(this.directionalLight);
        
        // 添加光源辅助器（调试用）
        if (window.location.search.includes('debug')) {
            const helper = new THREE.DirectionalLightHelper(this.directionalLight, 1);
            this.scene.add(helper);
        }
    }
    
    setupControls() {
        this.controls = new OrbitControls(this.camera, this.canvas);
        
        // 配置控制器参数
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.05;
        this.controls.screenSpacePanning = false;
        this.controls.minDistance = 2;
        this.controls.maxDistance = 50;
        this.controls.maxPolarAngle = Math.PI / 2;
        
        // 自动旋转
        this.controls.autoRotate = false;
        this.controls.autoRotateSpeed = 0.5;
    }
    
    setupPostProcessing() {
        // 创建效果合成器
        this.composer = new EffectComposer(this.renderer);
        
        // 渲染通道
        this.renderPass = new RenderPass(this.scene, this.camera);
        this.composer.addPass(this.renderPass);
        
        // 辉光效果
        this.bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
        
        // 胶片效果
        this.filmPass = new FilmPass(0.35, 0.025, 648, false);
        
        // 复制通道（最终输出）
        const copyPass = new ShaderPass(CopyShader);
        copyPass.renderToScreen = true;
        this.composer.addPass(copyPass);
    }
    
    /**
     * 2. 场景构建
     */
    createBasicScene() {
        this.clearScene();
        
        // 创建地面
        const groundGeometry = new THREE.PlaneGeometry(20, 20);
        const groundMaterial = new THREE.MeshStandardMaterial({
            color: 0x808080,
            roughness: 0.8,
            metalness: 0.2
        });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        this.scene.add(ground);
        this.sceneObjects.set('ground', ground);
        
        // 创建基础几何体
        this.createGeometryShowcase();
        
        // 添加粒子系统
        this.createParticleSystem();
        
        this.currentScene = 'basic';
    }
    
    createGeometryShowcase() {
        const geometries = [
            { geo: new THREE.BoxGeometry(1, 1, 1), pos: [-3, 0.5, 0], color: 0xff6b6b },
            { geo: new THREE.SphereGeometry(0.5, 32, 32), pos: [-1, 0.5, 0], color: 0x4ecdc4 },
            { geo: new THREE.ConeGeometry(0.5, 1, 8), pos: [1, 0.5, 0], color: 0x45b7d1 },
            { geo: new THREE.CylinderGeometry(0.5, 0.5, 1, 16), pos: [3, 0.5, 0], color: 0xf9ca24 },
            { geo: new THREE.TorusGeometry(0.4, 0.2, 16, 100), pos: [0, 1.5, -2], color: 0x6c5ce7 }
        ];
        
        geometries.forEach((item, index) => {
            const material = new THREE.MeshStandardMaterial({
                color: item.color,
                roughness: 0.4,
                metalness: 0.6
            });
            
            const mesh = new THREE.Mesh(item.geo, material);
            mesh.position.set(...item.pos);
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            mesh.userData = { type: 'geometry', index };
            
            this.scene.add(mesh);
            this.sceneObjects.set(`geometry_${index}`, mesh);
            
            // 添加到动画对象列表
            this.animatedObjects.push({
                object: mesh,
                originalY: mesh.position.y,
                speed: 0.5 + Math.random() * 0.5
            });
        });
    }
    
    createParticleSystem() {
        const particleCount = 1000;
        const positions = new Float32Array(particleCount * 3);
        const colors = new Float32Array(particleCount * 3);
        
        for (let i = 0; i < particleCount; i++) {
            positions[i * 3] = (Math.random() - 0.5) * 20;
            positions[i * 3 + 1] = Math.random() * 10;
            positions[i * 3 + 2] = (Math.random() - 0.5) * 20;
            
            colors[i * 3] = Math.random();
            colors[i * 3 + 1] = Math.random();
            colors[i * 3 + 2] = Math.random();
        }
        
        const particleGeometry = new THREE.BufferGeometry();
        particleGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
        particleGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
        
        const particleMaterial = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: true,
            transparent: true,
            opacity: 0.6
        });
        
        const particles = new THREE.Points(particleGeometry, particleMaterial);
        this.scene.add(particles);
        this.sceneObjects.set('particles', particles);
    }
    
    loadEnvironmentMap() {
        // 创建简单的天空盒
        const loader = new THREE.CubeTextureLoader();
        const urls = [
            'data:image/svg+xml;base64,' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#87CEEB"/></svg>'),
            'data:image/svg+xml;base64,' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#87CEEB"/></svg>'),
            'data:image/svg+xml;base64=' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#98D8E8"/></svg>'),
            'data:image/svg+xml;base64=' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#2F4F4F"/></svg>'),
            'data:image/svg+xml;base64=' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#87CEEB"/></svg>'),
            'data:image/svg+xml;base64=' + btoa('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"><rect width="512" height="512" fill="#87CEEB"/></svg>')
        ];
        
        const envMap = loader.load(urls);
        this.scene.background = envMap;
        this.scene.environment = envMap;
    }
    
    /**
     * 3. 实现交互性
     */
    setupEventListeners() {
        // 窗口大小变化
        window.addEventListener('resize', this.onWindowResize.bind(this));
        
        // 鼠标交互
        this.canvas.addEventListener('click', this.onMouseClick.bind(this));
        this.canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
        
        // 键盘交互
        window.addEventListener('keydown', this.onKeyDown.bind(this));
        
        // UI控件
        this.setupUIControls();
    }
    
    setupUIControls() {
        // 场景选择器
        const sceneSelector = document.getElementById('scene-selector');
        sceneSelector.addEventListener('change', (e) => {
            this.switchScene(e.target.value);
        });
        
        // 环境光强度
        const ambientIntensity = document.getElementById('ambient-intensity');
        ambientIntensity.addEventListener('input', (e) => {
            this.settings.ambientIntensity = parseFloat(e.target.value);
            this.ambientLight.intensity = this.settings.ambientIntensity;
        });
        
        // 方向光强度
        const directionalIntensity = document.getElementById('directional-intensity');
        directionalIntensity.addEventListener('input', (e) => {
            this.settings.directionalIntensity = parseFloat(e.target.value);
            this.directionalLight.intensity = this.settings.directionalIntensity;
        });
        
        // 线框模式切换
        document.getElementById('toggle-wireframe').addEventListener('click', () => {
            this.toggleWireframe();
        });
        
        // 阴影切换
        document.getElementById('toggle-shadows').addEventListener('click', () => {
            this.toggleShadows();
        });
        
        // 添加随机物体
        document.getElementById('add-object').addEventListener('click', () => {
            this.addRandomObject();
        });
        
        // 重置场景
        document.getElementById('reset-scene').addEventListener('click', () => {
            this.createBasicScene();
        });
    }
    
    onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.composer.setSize(window.innerWidth, window.innerHeight);
    }
    
    onMouseClick(event) {
        this.updateMousePosition(event);
        
        this.raycaster.setFromCamera(this.mouse, this.camera);
        const intersects = this.raycaster.intersectObjects(this.scene.children, true);
        
        if (intersects.length > 0) {
            const object = intersects[0].object;
            this.selectObject(object);
        } else {
            this.deselectObject();
        }
    }
    
    onMouseMove(event) {
        this.updateMousePosition(event);
        
        // 实现鼠标悬停效果
        this.raycaster.setFromCamera(this.mouse, this.camera);
        const intersects = this.raycaster.intersectObjects(this.scene.children, true);
        
        if (intersects.length > 0) {
            this.canvas.style.cursor = 'pointer';
        } else {
            this.canvas.style.cursor = 'grab';
        }
    }
    
    updateMousePosition(event) {
        const rect = this.canvas.getBoundingClientRect();
        this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    }
    
    selectObject(object) {
        this.deselectObject();
        
        this.selectedObject = object;
        
        // 高亮效果
        if (object.material) {
            object.userData.originalEmissive = object.material.emissive.clone();
            object.material.emissive.setHex(0x444444);
        }
    }
    
    deselectObject() {
        if (this.selectedObject && this.selectedObject.material) {
            this.selectedObject.material.emissive.copy(this.selectedObject.userData.originalEmissive || new THREE.Color(0x000000));
        }
        this.selectedObject = null;
    }
    
    onKeyDown(event) {
        switch (event.code) {
            case 'Digit1':
                this.switchScene('basic');
                break;
            case 'Digit2':
                this.switchScene('lighting');
                break;
            case 'Digit3':
                this.switchScene('materials');
                break;
            case 'Digit4':
                this.switchScene('animation');
                break;
            case 'Digit5':
                this.switchScene('postprocessing');
                break;
            case 'Space':
                event.preventDefault();
                this.controls.autoRotate = !this.controls.autoRotate;
                break;
        }
    }
    
    /**
     * 4. 实现动画
     */
    animate() {
        requestAnimationFrame(this.animate.bind(this));
        
        const deltaTime = this.clock.getDelta();
        const elapsedTime = this.clock.getElapsedTime();
        
        // 更新控制器
        this.controls.update();
        
        // 更新动画混合器
        this.mixers.forEach(mixer => mixer.update(deltaTime));
        
        // 更新动画对象
        this.updateAnimations(elapsedTime);
        
        // 更新粒子系统
        this.updateParticles(elapsedTime);
        
        // 渲染
        if (this.settings.enablePostProcessing) {
            this.composer.render();
        } else {
            this.renderer.render(this.scene, this.camera);
        }
        
        // 更新性能统计
        this.updateStats();
    }
    
    updateAnimations(elapsedTime) {
        this.animatedObjects.forEach(item => {
            if (item.object && item.object.parent) {
                item.object.position.y = item.originalY + Math.sin(elapsedTime * item.speed) * 0.2;
                item.object.rotation.y = elapsedTime * 0.5;
            }
        });
    }
    
    updateParticles(elapsedTime) {
        const particles = this.sceneObjects.get('particles');
        if (particles) {
            particles.rotation.y = elapsedTime * 0.1;
            
            const positions = particles.geometry.attributes.position.array;
            for (let i = 1; i < positions.length; i += 3) {
                positions[i] += Math.sin(elapsedTime + positions[i * 3]) * 0.01;
            }
            particles.geometry.attributes.position.needsUpdate = true;
        }
    }
    
    /**
     * 5. 视觉效果增强
     */
    switchScene(sceneName) {
        this.currentScene = sceneName;
        document.getElementById('scene-selector').value = sceneName;
        
        switch (sceneName) {
            case 'basic':
                this.createBasicScene();
                this.settings.enablePostProcessing = false;
                break;
            case 'lighting':
                this.createLightingDemo();
                this.settings.enablePostProcessing = false;
                break;
            case 'materials':
                this.createMaterialsDemo();
                this.settings.enablePostProcessing = false;
                break;
            case 'animation':
                this.createAnimationDemo();
                this.settings.enablePostProcessing = false;
                break;
            case 'postprocessing':
                this.createPostProcessingDemo();
                this.settings.enablePostProcessing = true;
                break;
        }
    }
    
    createLightingDemo() {
        this.clearScene();
        
        // 创建地面
        const groundGeometry = new THREE.PlaneGeometry(20, 20);
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x404040 });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        this.scene.add(ground);
        
        // 添加多个点光源
        const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff];
        colors.forEach((color, index) => {
            const light = new THREE.PointLight(color, 1, 10);
            const angle = (index / colors.length) * Math.PI * 2;
            light.position.set(Math.cos(angle) * 3, 2, Math.sin(angle) * 3);
            light.castShadow = true;
            this.scene.add(light);
            
            // 添加光源可视化
            const lightGeometry = new THREE.SphereGeometry(0.1, 16, 16);
            const lightMaterial = new THREE.MeshBasicMaterial({ color });
            const lightMesh = new THREE.Mesh(lightGeometry, lightMaterial);
            lightMesh.position.copy(light.position);
            this.scene.add(lightMesh);
            
            this.pointLights.push({ light, mesh: lightMesh, angle: angle });
        });
        
        // 中央物体
        const geometry = new THREE.IcosahedronGeometry(1, 1);
        const material = new THREE.MeshStandardMaterial({
            color: 0xffffff,
            roughness: 0.1,
            metalness: 0.9
        });
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.y = 1;
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        this.scene.add(mesh);
    }
    
    createMaterialsDemo() {
        this.clearScene();
        
        // 创建地面
        const groundGeometry = new THREE.PlaneGeometry(20, 20);
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x404040 });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        this.scene.add(ground);
        
        // 不同材质的球体
        const materials = [
            new THREE.MeshBasicMaterial({ color: 0xff6b6b }),
            new THREE.MeshLambertMaterial({ color: 0x4ecdc4 }),
            new THREE.MeshPhongMaterial({ color: 0x45b7d1, shininess: 100 }),
            new THREE.MeshStandardMaterial({ color: 0xf9ca24, roughness: 0.2, metalness: 0.8 }),
            new THREE.MeshPhysicalMaterial({ 
                color: 0x6c5ce7, 
                roughness: 0.1, 
                metalness: 0.9,
                clearcoat: 1.0,
                clearcoatRoughness: 0.1
            })
        ];
        
        materials.forEach((material, index) => {
            const geometry = new THREE.SphereGeometry(0.8, 32, 32);
            const mesh = new THREE.Mesh(geometry, material);
            mesh.position.set((index - 2) * 2.5, 1, 0);
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            this.scene.add(mesh);
        });
    }
    
    createAnimationDemo() {
        this.clearScene();
        
        // 创建地面
        const groundGeometry = new THREE.PlaneGeometry(20, 20);
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x404040 });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        this.scene.add(ground);
        
        // 创建复杂动画对象
        for (let i = 0; i < 10; i++) {
            const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
            const material = new THREE.MeshStandardMaterial({
                color: new THREE.Color().setHSL(i / 10, 1, 0.5)
            });
            const mesh = new THREE.Mesh(geometry, material);
            
            const angle = (i / 10) * Math.PI * 2;
            mesh.position.set(Math.cos(angle) * 3, 0.5, Math.sin(angle) * 3);
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            
            this.scene.add(mesh);
            
            this.animatedObjects.push({
                object: mesh,
                originalY: mesh.position.y,
                speed: 1 + i * 0.2,
                rotationSpeed: 0.5 + i * 0.1
            });
        }
    }
    
    createPostProcessingDemo() {
        this.createBasicScene();
        
        // 启用后处理效果
        this.composer.removePass(this.bloomPass);
        this.composer.removePass(this.filmPass);
        
        this.composer.insertPass(this.bloomPass, 1);
        this.composer.insertPass(this.filmPass, 2);
    }
    
    /**
     * 工具方法
     */
    clearScene() {
        // 清理动画对象
        this.animatedObjects = [];
        this.pointLights = [];
        
        // 清理场景对象
        this.sceneObjects.forEach((object, key) => {
            if (key !== 'ground') {
                this.scene.remove(object);
                if (object.geometry) object.geometry.dispose();
                if (object.material) {
                    if (Array.isArray(object.material)) {
                        object.material.forEach(mat => mat.dispose());
                    } else {
                        object.material.dispose();
                    }
                }
            }
        });
        
        // 清理点光源
        this.scene.children = this.scene.children.filter(child => {
            if (child.type === 'PointLight' && child !== this.directionalLight) {
                return false;
            }
            return true;
        });
        
        this.sceneObjects.clear();
    }
    
    toggleWireframe() {
        this.settings.wireframeMode = !this.settings.wireframeMode;
        
        this.scene.traverse((object) => {
            if (object.isMesh && object.material) {
                if (Array.isArray(object.material)) {
                    object.material.forEach(mat => {
                        mat.wireframe = this.settings.wireframeMode;
                    });
                } else {
                    object.material.wireframe = this.settings.wireframeMode;
                }
            }
        });
    }
    
    toggleShadows() {
        this.settings.enableShadows = !this.settings.enableShadows;
        this.renderer.shadowMap.enabled = this.settings.enableShadows;
        
        this.scene.traverse((object) => {
            if (object.isMesh) {
                object.castShadow = this.settings.enableShadows;
                object.receiveShadow = this.settings.enableShadows;
            }
        });
    }
    
    addRandomObject() {
        const geometries = [
            new THREE.BoxGeometry(1, 1, 1),
            new THREE.SphereGeometry(0.5, 16, 16),
            new THREE.ConeGeometry(0.5, 1, 8),
            new THREE.CylinderGeometry(0.3, 0.3, 1, 8)
        ];
        
        const geometry = geometries[Math.floor(Math.random() * geometries.length)];
        const material = new THREE.MeshStandardMaterial({
            color: new THREE.Color().setHSL(Math.random(), 1, 0.5),
            roughness: Math.random(),
            metalness: Math.random()
        });
        
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(
            (Math.random() - 0.5) * 10,
            Math.random() * 3 + 0.5,
            (Math.random() - 0.5) * 10
        );
        mesh.rotation.set(
            Math.random() * Math.PI,
            Math.random() * Math.PI,
            Math.random() * Math.PI
        );
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        
        this.scene.add(mesh);
        
        this.animatedObjects.push({
            object: mesh,
            originalY: mesh.position.y,
            speed: 0.5 + Math.random() * 1.5
        });
    }
    
    updateStats() {
        this.frameCount++;
        const currentTime = performance.now();
        
        if (currentTime - this.lastTime >= 1000) {
            this.fps = Math.round((this.frameCount * 1000) / (currentTime - this.lastTime));
            this.frameCount = 0;
            this.lastTime = currentTime;
            
            // 更新统计信息
            document.getElementById('fps').textContent = this.fps;
            document.getElementById('object-count').textContent = this.scene.children.length;
            
            // 计算三角形数量
            let triangleCount = 0;
            this.scene.traverse((object) => {
                if (object.isMesh && object.geometry) {
                    if (object.geometry.index) {
                        triangleCount += object.geometry.index.count / 3;
                    } else {
                        triangleCount += object.geometry.attributes.position.count / 3;
                    }
                }
            });
            document.getElementById('triangle-count').textContent = Math.round(triangleCount);
        }
    }
}

// 启动应用
window.addEventListener('DOMContentLoaded', () => {
    new ThreeJSApp();
});